server {
  listen unix:/var/vcap/data/blobstore/backend.sock;
  listen <%= p("blobstore.port") %> ssl;
  <% if p('blobstore.ipv6_listen') %>listen [::]:<%= p('blobstore.port') %> ssl;<% end %>


  server_name "";

  access_log  /var/vcap/sys/log/blobstore/blobstore_access.log common_event_format;
  error_log   /var/vcap/sys/log/blobstore/blobstore_error.log;

  client_max_body_size <%= p("blobstore.max_upload_size") %>;

  <% if p('blobstore.allow_http') %>
  error_page 497 = @handler;
  <% end %>

  ssl_certificate /var/vcap/jobs/blobstore/config/server_tls_cert.pem;
  ssl_certificate_key /var/vcap/jobs/blobstore/config/server_tls_private_key.pem;
  <% if p('blobstore.tls.ssl_prefer_server_ciphers') %>ssl_prefer_server_ciphers On;<% end %>
  ssl_protocols <%= p('blobstore.tls.ssl_protocols') %>;
  ssl_ciphers <%= p('blobstore.tls.ssl_ciphers') %>;

  location ~* ^/(?<object_id>[a-fA-F0-9][a-fA-F0-9]\/.+) {
    root /var/vcap/store/blobstore/store/;

    dav_methods DELETE PUT;
    create_full_put_path on;

    auth_basic "Blobstore Read";
    auth_basic_user_file read_users;

    limit_except GET {
      auth_basic "Blobstore Write";
      auth_basic_user_file write_users;
    }
  }

  location /internal {
    internal;
    alias /var/vcap/store/blobstore/store/;

    dav_methods DELETE PUT;
    create_full_put_path on;
  }

<% if p('blobstore.enable_signed_urls') %>
  location ~* ^/signed/(?<object_id>.+)$ {
    if ( $request_method !~ ^(GET|PUT|HEAD)$ ) {
      return 405;
    }

    # Variable to be passed are secure token, timestamp, expiration date
    secure_link_hmac $arg_st,$arg_ts,$arg_e;

    # Secret key
    secure_link_hmac_secret <%= p('blobstore.secret') %>;

    # Message to be verified
    secure_link_hmac_message $request_method$object_id$arg_ts$arg_e;

    # Cryptographic hash function to be used
    secure_link_hmac_algorithm sha256;

    if ($secure_link_hmac != "1") {
      return 403;
    }

    rewrite ^/signed/(.*)$ /internal/$object_id;
  }
<% end %>

  <% if p('blobstore.nginx.enable_metrics_endpoint') %>
  location /stats {
    # Config for basic metrics module: ngx_http_stub_status_module
    stub_status;
    access_log off;
    allow 127.0.0.1;
    allow ::1;
    deny all;
  }
  <% end %>

  location @handler {
    proxy_pass http://unix:/var/vcap/data/blobstore/backend.sock:$request_uri;
  }
}
